import axios from 'axios'; // 引入axios
import qs from 'qs'; // 引入qs
import Global from './global'; // 引入global.js
import Vue from 'vue';
// axios 默认配置  更多配置查看Axios中文文档
axios.defaults.timeout = 1000000; // 超时默认值
axios.defaults.baseURL = Global.baseURL; // 默认baseURL
// axios.defaults.responseType  = 'json'         // 默认数据响应类型
axios.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8';
///axios.defaults.withCredentials = true; // 表示跨域请求时是否需要使用凭证

//登录标识位置
var loginInx = location.href.indexOf('/login?');
//截取参数 , 截取问号后面的字符串
var queryString = location.href.substring(location.href.indexOf(location.origin) + location.origin.length + 1).split('?');
var queryArr = is_empty(queryString[1]) ? '' : queryString[1].split('&');
var queryObj = {};
//参数组合对象
for (var i = queryArr.length - 1; i >= 0; i--) {
    var temp = queryArr[i].split('=');
    queryObj[temp[0]] = temp[1];
}
if (loginInx > -1) {
    //登录token是否空
    if (is_empty(queryObj.token)) {
        queryObj.token = '--';
    }
    sessionStorage.setItem('token', queryObj.token);
    delete queryObj.token;
}

if (!is_empty(queryObj.CheckSchoolAppCode)) {
    sessionStorage.setItem('CheckSchoolAppCode', queryObj.CheckSchoolAppCode);
    delete queryObj.CheckSchoolAppCode;
}

//请求服务器host字段为空,则使用当前地址的host
if (!is_empty(queryObj.host)) {
    sessionStorage.setItem('host', queryObj.host);
    redirectUrl += '&host=' + queryObj.host;
    delete queryObj.host;
} else if (is_empty(sessionStorage.getItem('host'))) {
    sessionStorage.setItem('host', location.host);
    redirectUrl += '&host=' + location.host;
}
//设置websocket请求地址
var ip = sessionStorage.getItem('host').split(":");
sessionStorage.setItem('user_chat_url', 'ws://' + ip[0] + ':7272')
//请求服务器procotol字段为空,则使用当前地址的procotol
if (!is_empty(queryObj.protocol)) {
    sessionStorage.setItem('protocol', queryObj.protocol);
    redirectUrl += '&protocol=' + queryObj.protocol;
    delete queryObj.protocol;
} else if (is_empty(sessionStorage.getItem('protocol'))) {
    sessionStorage.setItem('protocol', location.protocol.replace(':', ''));
    redirectUrl += '&procotol=' + location.protocol.replace(':', '');
}
var paramString = '';
//跳转的路由
if (!is_empty(queryObj.routerUrl)) {
    paramString = queryObj.routerUrl;
    delete queryObj.routerUrl;
}
//剩下的参数作为跳转的参数
paramString += Object.keys(queryObj).length === 0 ? '' : '?';
let inx = 0;
Object.keys(queryObj).forEach(function(key) {
    paramString += (inx === 0 ? '' : '&') + key + '=' + queryObj[key];
    inx++;
})
sessionStorage.setItem('paramString', paramString);
//设置跳转其他内部平台的地址 例如 后台,个人中心
var redirectUrl = '/login?token=' + queryObj.token;
sessionStorage.setItem('redirect_params', '/login?token=' + sessionStorage.getItem('token'));
// 本地运行调试
localStorage.setItem('token', sessionStorage.getItem('token'))
//设置请求地址
sessionStorage.setItem('host_addr', sessionStorage.getItem('protocol') + '://' + sessionStorage.getItem('host'));
// sessionStorage.setItem('host_addr', 'http://172.16.13.84');
if (!is_empty(queryObj.ItcJwtToken)) {
    sessionStorage.setItem('ItcJwtToken', queryObj.ItcJwtToken);
    delete queryObj.ItcJwtToken;
}

axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? sessionStorage.getItem('host_addr') : '/'
// http request 拦截器
// 在ajax发送之前拦截 比如对所有请求统一添加header token
var company = 'BL';
var device_name = 'TE-0600R';
axios.interceptors.request.use(
    config => {
        if (Global.access_token) {
            config.headers.Authorization = `Bearer ${Global.access_token}`;
            config.headers.DecisionPlatform = `${Global.decisionPlatform}`;
            config.headers.token = sessionStorage.getItem('token')
            config.headers.ItcJwtToken = sessionStorage.getItem('ItcJwtToken')
            config.headers.CheckSchoolAppCode = sessionStorage.getItem('CheckSchoolAppCode')
            var actioncodeArr = config.url.split('/');
            if (config.method == 'post' || config.method == 'put') {
                var requestData = config.data;
                delete config.data;
                config.data = {};
                config.data.company = company;
                config.data.device_name = device_name;
                config.data.sign = `${Global.access_token}`;
                config.data.actioncode = config.method + '_' + actioncodeArr[actioncodeArr.length - 1];
                config.data.data = requestData;
                if (config.headers['content-type'] != 'multipart/form-data') {
                    config.data = qs.stringify(config.data);
                }
            } else if (config.method == 'get' || config.method == 'delete') {
                if (config.params === undefined) {
                    config.params = {};
                }
                if (!config.params.hasOwnProperty('company')) {
                    var requestData = config.params;
                    delete config.params;
                    config.params = {};
                    config.params.company = company;
                    config.params.device_name = device_name;
                    config.params.sign = `${Global.access_token}`;
                    config.params.actioncode = config.method + '_' + actioncodeArr[actioncodeArr.length - 1];
                    config.params.data = requestData;
                }
            }
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

// http response 拦截器
// ajax请求回调之前拦截 对请求返回的信息做统一处理 比如error为401无权限则跳转到登陆界面
axios.interceptors.response.use(function(response) {
    // 对响应数据做点什么
    if (!response.config.hasOwnProperty('func')) {
        response.config.func = {};
    }
    if (response.data.hasOwnProperty('data')) {
        var responseData = handleResponseData(response.data, 'need');
    } else {
        var responseData = response.data;
    }
    // 对响应数据做点什么
    Vue.prototype.Ajax_callback(responseData, response.config.func)
    return response;
}, function(error) {

    // 对响应错误做点什么
    if (error.response.status == 401) {
        var config = error.config;
        get_access_token(function() {
            //重新发送请求，并执行回调
            if (config.method == 'post' || config.method == 'put') {
                //qs.stringify反向转换成对象
                config.data = qs.parse(config.data);
            }
            if (!config.hasOwnProperty('func')) {
                config.func = {};
            }
            //执行之前的ajax请求
            axios(config).then(response => Vue.prototype.Ajax_callback(response.data, config.func));
        });
    } else if (error.response.status == 505) {
        //2后跳回首页
        Vue.prototype.$message.error("已过期，请登录")
        setTimeout(() => {
            window.location.href = location.protocol + '//' + location.host.split(':')[0];
        }, 1500)
    } else {
        // 对响应数据做点什么
        if (!error.response.config.hasOwnProperty('func')) {
            error.response.config.func = {};
        }
        Vue.prototype.Ajax_callback(error.response.data, error.response.config.func)
    }
    return Promise.reject(error);
});

export default axios; // 这句千万不能漏下！！！

/**
 * 获取access_token 方法封装
 */
/*function get_access_token(callback) {
    axios.get('/accessToken',{
        params:{
            client_id:Global.client_id ,
            secret: Global.secret
        }})
        .then(response => {

            let data = response.data.data
            Global.access_token = data.access_token;
            localStorage.setItem('token', Global.access_token);
            callback();
        });
}*/

/**
 * 获取access_token 方法封装
 */
function get_access_token(callback) {
    axios.get('/accessToken', {
            params: {
                company: 'BL',
                device_name: 'TE-0600R',
                data: {
                    client_id: Global.client_id,
                    secret: Global.secret
                }
            }
        })
        .then(response => {
            let data = response.data.data;
            Global.access_token = data.access_token;
            localStorage.setItem('token', Global.access_token);
            callback();
        });
}

/**
 * 获取cookie里某个键的值
 */
function getCookie(name) {
    var strcookie = document.cookie; //获取cookie字符串
    var arrcookie = strcookie.split("; "); //分割
    //遍历匹配
    for (var i = 0; i < arrcookie.length; i++) {
        var arr = arrcookie[i].split("=");
        if (arr[0] == name) {
            return arr[1];
        }
    }
    return "";
}